package com.bing.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author 徐
 * @version 1.0
 * 控制器：取出数据向request域
 */
@Controller
public class RequestController {

    @GetMapping("/login")
    public String login(HttpServletRequest request){
        //向request域中添加数据
        request.setAttribute("user","老韩");
        //向session域中添加数据
        request.getSession().setAttribute("website","http://baidu.com");
        //请求转发到 ok
        return "forward:/ok";
    }

    /**
     * 从request中取出数据
     * 从session域中取出数据
     * @ResponseBody 返回json字符串，不走视图解析器
     * @param username
     * @return
     */
    @GetMapping("/ok")
    @ResponseBody
    public String ok(@RequestAttribute(value = "user",required = false) String username,
                     @SessionAttribute(value = "website",required = false) String website,
                     HttpServletRequest request){
        //获取到request中的数据
        System.out.println("username =" + username);
        //通过servlet api获取 username
        System.out.println("username-servlet api =" + request.getAttribute("user"));

        //从session域中获取数据
        System.out.println("website= " + website);
        //通过session api获取 website
        System.out.println("website-servlet api =" + request.getSession().getAttribute("website"));
        return "success";
    }

    //响应注册请求
    @GetMapping("/register")
    public String register(Map<String,Object> map, Model model,
                           HttpServletResponse response){
        //如果一个注册请求,会将注册数据封装到 map 或者 model
        //map和model中的数据，会被放入到 request域中
        map.put("user","hspedu");
        map.put("job","java架构师");
        model.addAttribute("sal",8000);

        //测试response的使用
        //演示创建cookie,并通过response 添加到客户端/浏览器
        Cookie cookie = new Cookie("email", "hspedu@sohu.com");
        response.addCookie(cookie);
        //请求转发
        return "forward:/registerOk";
    }

    //取出注册请求携带的数据
    @GetMapping("/registerOk")
    @ResponseBody
    public String registerOk(HttpServletRequest request){
        System.out.println("user-" + request.getAttribute("user"));
        System.out.println("job-" + request.getAttribute("job"));
        System.out.println("sal-" + request.getAttribute("sal"));

        return "success";
    }
}
